package Work0609;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class TestServer {

	private AsynchronousServerSocketChannel channel = null;

	public TestServer(int port) {

		try {
			channel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port));
		} catch (IOException e) {
			e.printStackTrace();
		}

		channel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

			@Override
			public void completed(AsynchronousSocketChannel socket, Void attachment) {
				channel.accept(attachment, this);
				ByteBuffer byteBuffer = ByteBuffer.allocate(64);
				socket.read(byteBuffer);
				byteBuffer.flip();
				System.out.println(new String(byteBuffer.array()));
			}

			@Override
			public void failed(Throwable exc, Void attachment) {
				System.out.println("建立通信失败");
			}
		});

	}

}